# 通用
import os, configparser, json, requests, time

# 获取执行程序路径
program_path = os.path.dirname(os.path.dirname(__file__))

# 读取配置文件，如果配置文件不存在则创建
config_file_path = os.path.join(program_path, 'config/zabbix_patrol.ini')
config = configparser.RawConfigParser()
config.read(config_file_path, encoding="utf-8")

# 获取指定节点的指定key的value
zb_api = json.loads(config.get("ZABBIX", "zb_api"))
zb_username = json.loads(config.get("ZABBIX", "zb_username"))
zb_password = json.loads(config.get("ZABBIX", "zb_password"))

# 调用zabbix api，发送JSON数据
def get_response(url, header, data):
    try:
        request = requests.get(url=url, data=data, headers=header).content.decode()
        response = json.loads(request)
    except:
        with open("error.log", "a+", encoding="utf8") as f:
            f.write(time.strftime("%Y-%m-%d %H:%M:%S") + "data:{}".format(data) + "失败\n")
    else:
        return response


class ZabbixTools:
    def __init__(self):
        # 定义zabbix api
        self.url = zb_api
        self.header = {"Content-Type": "application/json"}
        self.authid = self.user_login()

    # 用户登入
    def user_login(self):
        """
        登入，返回token
        """
        data = json.dumps({
            "jsonrpc": "2.0",
            "method": "user.login",
            "params": {
                "user": zb_username,
                "password": zb_password,
            },
            "id": 0
        })
        res = get_response(self.url, self.header, data)
        authid = res['result']
        return authid

    # host.get 查找主机名
    def host_get(self, range):
        data = json.dumps({
            "jsonrpc": "2.0",
            "method": "host.get",
            "params": {
                "output": range,
                "selectGroups": ["name"],
            },
            "auth": self.authid,
            "id": 1,
        })
        return get_response(self.url, self.header, data)

    def hostname_get(self, hostid):
        resp = self.host_get(range=["hostid", "name"])
        for i in resp["result"]:
            # 获取主机名
            hostname = str(i["name"])
            # 比对 hostid 相同后返回hostname。
            if str(i["hostid"]) == hostid:
                return hostname

    def item_get(self, hostid, key="", range="extend"):
        data = json.dumps({
            "jsonrpc": "2.0",
            "method": "item.get",
            "params": {
                "output": range,
                "hostids": hostid,
                "search": {
                    "key_": key
                },
            },
            "auth": self.authid,
            "id": 1
        })
        return get_response(self.url, self.header, data)

    def itemid_get(self, hostid, interface):

        # 检索针对该 hostid 的所有 监控项 的数据。
        resp = self.item_get(hostid)

        # 过滤
        key_itemid_dict = {}
        for i in resp["result"]:
            # 条件1 过滤ifHCInOctets、ifHCOutOctets监控项。
            if "ifHCInOctets" in str(i["key_"]) or "ifHCOutOctets" in str(i["key_"]):
                # 条件2 过滤name中包含10GE、25GE、40GE、100GE的监控项。
                if "10GE" in str(i["name"]) or "25GE" in str(i["name"]) or "40GE" in str(i["name"]) or \
                        "100GE" in str(i["name"]):
                    # 条件3 匹配interface
                    if interface == str(i["name"]).split(".")[0]:
                        # 获取key格式(net.if.in[ifHCInOctets.44])
                        key = str(i["key_"])
                        # 获取itemid
                        itemid = str(i["itemid"])
                        # 将key和itemid加入字典
                        key_itemid_dict[key] = itemid
        return key_itemid_dict

    def speed_get(self, hostid, oid):
        resp = self.item_get(hostid, key="net.if.speed[ifHighSpeed.{}]".format(oid))
        for speed in resp["result"]:
            # 获取最后速率值并返回
            speed_value = str(speed["lastvalue"])
            return speed_value

    def trigger_get(self, interface):
        data = json.dumps({
            "jsonrpc": "2.0",
            "method": "trigger.get",
            "params": {
                "output": ["description", "functions"],
                "selectFunctions": "extend",
                "search": {
                    "description": interface
                },
            },
            "auth": self.authid,
            "id": 1
        })
        return get_response(self.url, self.header, data)

    def triggerid_get(self, interface, itemid):
        resp = self.trigger_get(interface)
        for i in resp["result"]:
            # 查找传入进来itemid对应的triggerid。
            if itemid == i["functions"][0]["itemid"]:
                return i["functions"][0]["triggerid"]

    def trigger_create(self, name, expression):
        data = json.dumps({
            "jsonrpc": "2.0",
            "method": "trigger.create",
            "params": {
                "description": name,
                "expression": expression,
                "priority": 2
            },
            "auth": self.authid,
            "id": 1
        })
        return get_response(self.url, self.header, data)

    def trigger_update(self, triggerid, name, expression):
        data = json.dumps({
            "jsonrpc": "2.0",
            "method": "trigger.update",
            "params": {
                "triggerid": triggerid,
                "description": name,
                "expression": expression,
                "priority": 2,
                "tags": []
            },
            "auth": self.authid,
            "id": 1
        })
        return get_response(self.url, self.header, data)

    def trigger_delete(self, triggerid):
        data = json.dumps({
            "jsonrpc": "2.0",
            "method": "trigger.delete",
            "params": [triggerid],
            "auth": self.authid,
            "id": 1
        })
        return get_response(self.url, self.header, data)
